// DOM元素
const elements = {
  // 通知设置
  notificationsEnabled: document.getElementById('notifications-enabled'),
  notificationsTimeout: document.getElementById('notifications-timeout'),
  
  // 播放器设置
  defaultPlayer: document.getElementById('default-player'),
  useCustomPlayer: document.getElementById('use-custom-player'),
  customPlayerUrl: document.getElementById('custom-player-url'),
  
  // 下载器设置
  defaultDownloader: document.getElementById('default-downloader'),
  useCustomDownloader: document.getElementById('use-custom-downloader'),
  customDownloaderUrl: document.getElementById('custom-downloader-url'),
  autoOpenDownloader: document.getElementById('auto-open-downloader'),
  
  // 过滤规则
  filtersEnabled: document.getElementById('filters-enabled'),
  filterRules: document.getElementById('filter-rules'),
  
  // 存储设置
  autoClear: document.getElementById('auto-clear'),
  maxItems: document.getElementById('max-items'),
  clearAfterDays: document.getElementById('clear-after-days'),
  
  // 导入导出
  exportBtn: document.getElementById('export-btn'),
  importBtn: document.getElementById('import-btn'),
  importFile: document.getElementById('import-file'),
  
  // 重置按钮
  resetBtn: document.getElementById('reset-btn'),
  
  // 保存按钮
  saveBtn: document.getElementById('save-btn'),
  
  // 消息
  successMessage: document.getElementById('success-message'),
  errorMessage: document.getElementById('error-message'),
  
  // 标签页
  tabs: document.querySelectorAll('.tab'),
  tabContents: document.querySelectorAll('.tab-content')
};

// 默认设置
const defaultSettings = {
  notifications: {
    enabled: true,
    timeout: 5000
  },
  player: {
    useCustom: false,
    defaultPlayer: 'https://m3u8play.com/?url=',
    customPlayerUrl: ''
  },
  downloader: {
    useCustom: false,
    defaultDownloader: 'https://tools.thatwind.com/tool/m3u8downloader#',
    customDownloaderUrl: '',
    autoOpen: false
  },
  filters: {
    enabled: false,
    rules: []
  },
  storage: {
    autoClear: false,
    maxItems: 100,
    clearAfterDays: 7
  }
};

// 当前设置
let currentSettings = {};

// 初始化
async function initialize() {
  // 加载设置
  await loadSettings();
  
  // 添加事件监听器
  addEventListeners();
}

// 加载设置
async function loadSettings() {
  try {
    const result = await chrome.storage.sync.get({ settings: defaultSettings });
    currentSettings = result.settings;
    
    // 更新UI
    updateUI();
  } catch (error) {
    console.error('加载设置失败:', error);
    showError('加载设置失败！');
  }
}

// 更新UI
function updateUI() {
  // 通知设置
  elements.notificationsEnabled.checked = currentSettings.notifications.enabled;
  elements.notificationsTimeout.value = currentSettings.notifications.timeout;
  
  // 播放器设置
  elements.defaultPlayer.value = currentSettings.player.defaultPlayer;
  elements.useCustomPlayer.checked = currentSettings.player.useCustom;
  elements.customPlayerUrl.value = currentSettings.player.customPlayerUrl;
  elements.customPlayerUrl.disabled = !currentSettings.player.useCustom;
  
  // 下载器设置
  elements.defaultDownloader.value = currentSettings.downloader.defaultDownloader;
  elements.useCustomDownloader.checked = currentSettings.downloader.useCustom;
  elements.customDownloaderUrl.value = currentSettings.downloader.customDownloaderUrl;
  elements.customDownloaderUrl.disabled = !currentSettings.downloader.useCustom;
  elements.autoOpenDownloader.checked = currentSettings.downloader.autoOpen;
  
  // 过滤规则
  elements.filtersEnabled.checked = currentSettings.filters.enabled;
  elements.filterRules.value = currentSettings.filters.rules.join('\n');
  
  // 存储设置
  elements.autoClear.checked = currentSettings.storage.autoClear;
  elements.maxItems.value = currentSettings.storage.maxItems;
  elements.clearAfterDays.value = currentSettings.storage.clearAfterDays;
}

// 添加事件监听器
function addEventListeners() {
  // 标签页切换
  elements.tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      const tabId = tab.dataset.tab;
      switchTab(tabId);
    });
  });
  
  // 自定义播放器切换
  elements.useCustomPlayer.addEventListener('change', e => {
    elements.customPlayerUrl.disabled = !e.target.checked;
  });
  
  // 自定义下载器切换
  elements.useCustomDownloader.addEventListener('change', e => {
    elements.customDownloaderUrl.disabled = !e.target.checked;
  });
  
  // 导出设置
  elements.exportBtn.addEventListener('click', exportSettings);
  
  // 导入设置
  elements.importBtn.addEventListener('click', () => {
    elements.importFile.click();
  });
  
  elements.importFile.addEventListener('change', importSettings);
  
  // 重置设置
  elements.resetBtn.addEventListener('click', resetSettings);
  
  // 保存设置
  elements.saveBtn.addEventListener('click', saveSettings);
}

// 切换标签页
function switchTab(tabId) {
  // 更新标签按钮状态
  elements.tabs.forEach(tab => {
    tab.classList.toggle('active', tab.dataset.tab === tabId);
  });
  
  // 更新标签内容显示
  elements.tabContents.forEach(content => {
    content.classList.toggle('active', content.id === tabId);
  });
}

// 保存设置
async function saveSettings() {
  try {
    // 收集设置
    const settings = {
      notifications: {
        enabled: elements.notificationsEnabled.checked,
        timeout: parseInt(elements.notificationsTimeout.value) || 5000
      },
      player: {
        useCustom: elements.useCustomPlayer.checked,
        defaultPlayer: elements.defaultPlayer.value,
        customPlayerUrl: elements.customPlayerUrl.value
      },
      downloader: {
        useCustom: elements.useCustomDownloader.checked,
        defaultDownloader: elements.defaultDownloader.value,
        customDownloaderUrl: elements.customDownloaderUrl.value,
        autoOpen: elements.autoOpenDownloader.checked
      },
      filters: {
        enabled: elements.filtersEnabled.checked,
        rules: elements.filterRules.value.split('\n').filter(rule => rule.trim())
      },
      storage: {
        autoClear: elements.autoClear.checked,
        maxItems: parseInt(elements.maxItems.value) || 100,
        clearAfterDays: parseInt(elements.clearAfterDays.value) || 7
      }
    };
    
    // 保存设置
    await chrome.storage.sync.set({ settings });
    
    // 更新当前设置
    currentSettings = settings;
    
    showSuccess('设置已保存！');
  } catch (error) {
    console.error('保存设置失败:', error);
    showError('保存设置失败！');
  }
}

// 重置设置
async function resetSettings() {
  if (confirm('确定要重置所有设置吗？此操作不可撤销。')) {
    try {
      // 重置为默认设置
      await chrome.storage.sync.set({ settings: defaultSettings });
      
      // 更新当前设置
      currentSettings = { ...defaultSettings };
      
      // 更新UI
      updateUI();
      
      showSuccess('设置已重置！');
    } catch (error) {
      console.error('重置设置失败:', error);
      showError('重置设置失败！');
    }
  }
}

// 导出设置
function exportSettings() {
  const blob = new Blob([JSON.stringify(currentSettings, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'm3u8_detector_settings.json';
  a.click();
  URL.revokeObjectURL(url);
}

// 导入设置
function importSettings(event) {
  const file = event.target.files[0];
  if (!file) return;
  
  const reader = new FileReader();
  reader.onload = async (e) => {
    try {
      const settings = JSON.parse(e.target.result);
      
      // 验证设置格式
      if (!validateSettings(settings)) {
        throw new Error('无效的设置文件格式');
      }
      
      // 保存设置
      await chrome.storage.sync.set({ settings });
      
      // 更新当前设置
      currentSettings = settings;
      
      // 更新UI
      updateUI();
      
      showSuccess('设置已导入！');
    } catch (error) {
      console.error('导入设置失败:', error);
      showError('导入设置失败！请确保文件格式正确。');
    }
  };
  
  reader.readAsText(file);
  
  // 清除文件选择，允许重复导入相同文件
  event.target.value = '';
}

// 验证设置格式
function validateSettings(settings) {
  // 检查必需的顶级属性
  const requiredProps = ['notifications', 'player', 'downloader', 'filters', 'storage'];
  for (const prop of requiredProps) {
    if (!(prop in settings)) {
      return false;
    }
  }
  
  // 可以添加更详细的验证逻辑
  return true;
}

// 显示成功消息
function showSuccess(message) {
  elements.successMessage.textContent = message;
  elements.successMessage.style.display = 'block';
  elements.errorMessage.style.display = 'none';
  
  setTimeout(() => {
    elements.successMessage.style.display = 'none';
  }, 3000);
}

// 显示错误消息
function showError(message) {
  elements.errorMessage.textContent = message;
  elements.errorMessage.style.display = 'block';
  elements.successMessage.style.display = 'none';
  
  setTimeout(() => {
    elements.errorMessage.style.display = 'none';
  }, 3000);
}

// 当页面加载完成时初始化
document.addEventListener('DOMContentLoaded', initialize);